package com.qc.blogsystemplus.controller;

import com.qc.blogsystemplus.bean.ResponseBean;
import com.qc.blogsystemplus.bean.UserBean;
import com.qc.blogsystemplus.entity.User;
import com.qc.blogsystemplus.mapper.UserMapper;
import com.qc.blogsystemplus.service.UserService;
import com.qc.blogsystemplus.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequiresRoles("user")
    @GetMapping("/getalluser")
    public ResponseBean getAllUser() {
        List<User> list = userService.getAllUser();
        return new ResponseBean(200,"查询成功",list);
    }

    @RequiresRoles("user")
    @PostMapping("/updateuser")
    public ResponseBean updateUser(@RequestBody UserBean user) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
                String username = JWTUtil.getUsername(subject.getPrincipal().toString());
                user.setUsername(username);
                int re = userService.updateUser(user);
                    if (re != 0){
                        return new ResponseBean(200,"修改成功",user);
                } else {
                        return new ResponseBean(402,"修改错误",null);
            }
        } else {
            return new ResponseBean(401,"认证失败",null);
        }
    }

    @RequiresRoles("user")
    @GetMapping("/getuser")
    public ResponseBean getUser() {
        Subject subject = SecurityUtils.getSubject();
        if ( subject.isAuthenticated() ) {
            String username = JWTUtil.getUsername(subject.getPrincipal().toString());
            User user = userService.getUser(username);
            return new ResponseBean(200,"成功",user);
        } else {
            return new ResponseBean(401,"认证失败",null);
        }
    }
}
